<template>
  <a-modal :visible="cipher" title="修改密码" centered @cancel="clocipher" destroyOnClose @ok="ConfirmPassword">
    <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" :labelCol="{ span: 6 }"
                  :wrapperCol="{ span: 16 }">
      <a-form-model-item has-feedback label="密码" prop="password">
        <a-input v-model="ruleForm.password" type="password" autocomplete="off"/>
      </a-form-model-item>
      <a-form-model-item has-feedback label="确认密码" prop="checkPass">
        <a-input v-model="ruleForm.checkPass" type="password" autocomplete="off"/>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import md5 from "js-md5";

export default {
name: "EditPassword",
  props:{
    roleId:{type:[Number,String],request:true,}
  },
  data(){
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!!!"));
      } else {
        callback();
      }
    };
    return{
      cipher: false,
      ruleForm: {
        password: "",
        checkPass: "",
      },
      rules: {
        password: [{validator: validatePass, trigger: "change"}],
        checkPass: [{validator: validatePass2, trigger: "change"}],
      },
    }
  },
  methods:{
    ConfirmPassword() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.ruleForm))
          obj.id = this.roleId;
          obj.password = md5(obj.password)
          this.$api.editUser(obj).then((res) => {
            if (res.data.code == 0) {
              this.cipher = false;
              this.ruleForm = {};
              this.$message.info("密码重置成功!");
            }
          });
        }
      });
    },
    clocipher() {
      this.cipher = false;
      this.ruleForm = {};
    },
  },
}
</script>

<style scoped>

</style>